﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Koonsoft.HYCRM.Model;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Koonsoft.HYCRM.DAL
{
    public class BranchDAL
    {
        private Database database = DatabaseFactory.CreateDatabase("KOONCRMDB");

        /// <summary>
        /// 获取所有可用的分行信息
        /// </summary>
        /// <returns></returns>
        public List<BranchInfo> GetBranches()
        {
            var branches = new List<BranchInfo>();

            const string sql = "select * from branch where [Status]=0 order by branchID";

            using (var cmd = database.GetSqlStringCommand(sql))
            {
                DataSet ds;

                ds = database.ExecuteDataSet(cmd);

                if (ds != null)
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        branches.Add(new BranchInfo
                        {
                            BranchID = Convert.ToInt32(row["BranchID"]),
                            BranchName = row["BranchName"].ToString()
                        });
                    }
                }


            }

            return branches;
        }

        /// <summary>
        /// 根据登录名获取所属分行ID
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public int GetBranchIDByLoginName(string loginName)
        {
            const string sql = "Branch_GetBranchIDByLoginName";

            using (var cmd = database.GetStoredProcCommand(sql))
            {
                database.AddInParameter(cmd, "@loginName", DbType.String, loginName);

                return Convert.ToInt32(database.ExecuteScalar(cmd));
            }
        }

        /// <summary>
        /// 根据分行ID获取分行名称
        /// </summary>
        /// <param name="branchID"></param>
        /// <returns></returns>
        public string GetBranchNameByBranchID(int branchID)
        {
            const string sql = "select BranchName from branch where BranchID=@BranchID";

            using (var cmd = database.GetSqlStringCommand(sql))
            {
                database.AddInParameter(cmd, "@BranchID", DbType.Int32, branchID);

                return database.ExecuteScalar(cmd).ToString();
            }
        }
    }
}
